package utgame.com.fakelegendary.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.protobuf.InvalidProtocolBufferException;

import utgame.com.fakelegendary.R;
import utgame.com.fakelegendary.socket.ServerSession;
import utgame.UtMessage;
import utgame.UtMessage.MC_PlayerLogon;
import utgame.UtMessage.MS_PlayerLogon;
import utgame.UtMessage.MessagePacket.MessageType;

import static utgame.com.fakelegendary.common.Constant.UI_PlayerLogon;
import static utgame.com.fakelegendary.common.Constant.UI_RequestFriends;
import static utgame.com.fakelegendary.common.Constant.UI_UPDATE_WEBSOCKET_OPEN;
import static utgame.com.fakelegendary.common.Constant.UI_PlayerLogon;
import static utgame.com.fakelegendary.common.Constant.UI_UPDATE_WEBSOCKET_OPEN;


public class LogonActivity extends Activity implements View.OnClickListener{
    public static final String TAG = "LogonActivity";
    Button registerBtn = null;
    Button loginBtn = null;
    EditText useridEt = null;
    EditText passEt = null;
    TextView promptText = null;

    CheckBox rememberCb = null;

    private boolean mIsRegister = false;

    private long mExitTime = 0;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case UI_UPDATE_WEBSOCKET_OPEN:
                    Toast.makeText(getApplicationContext(), "websocket open", Toast.LENGTH_SHORT).show();

                    // 登陆
                    MC_PlayerLogon.Builder builder= UtMessage.MC_PlayerLogon.newBuilder();
                    builder.setName(useridEt.getText().toString());
                    builder.setPwd(passEt.getText().toString());
                    builder.setIsRegister(mIsRegister);

                    ServerSession.getInstance().sendMessage(MessageType.PlayerLogon, builder.build().toByteString());

                    break;
                case UI_PlayerLogon:
                    try {
                        MS_PlayerLogon msPlayerLogon = MS_PlayerLogon.parseFrom((byte[]) msg.obj);
                        if (msPlayerLogon.getRet() == 0){
                            Toast.makeText(getApplicationContext(), "register success", Toast.LENGTH_SHORT).show();

                            // 请求好友数据
                            UtMessage.MC_RequestFriends.Builder requestFriendsBuilder= UtMessage.MC_RequestFriends.newBuilder();
                            ServerSession.getInstance().sendMessage(MessageType.RequestFriends, requestFriendsBuilder.build().toByteString());


                        }
                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                    break;
                case UI_RequestFriends:
                    startActivity(new Intent(LogonActivity.this, MainActivity.class));
                    LogonActivity.this.finish();        // 否则程序退出时还会显示
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_logon);

        registerBtn = (Button) findViewById(R.id.registerBtn);
        registerBtn.setOnClickListener(this);

        loginBtn = (Button) findViewById(R.id.loginBtn);
        loginBtn.setOnClickListener(this);

        useridEt = (EditText) findViewById(R.id.userId);
        passEt = (EditText) findViewById(R.id.pass);
        promptText = (TextView) findViewById(R.id.promptText);

        rememberCb = (CheckBox) findViewById(R.id.cbRemember);
//        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
//                .readTimeout(10000L, TimeUnit.MILLISECONDS)
//                .build();
//        OkHttpUtils.initClient(okHttpClient);

        ServerSession.getInstance().addHandler(TAG, mHandler);
//        ServerSession.getInstance().startWebSocket();

        Context ctx = LogonActivity.this;
        SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);

        String name = sp.getString("name", "");
        String pwd = sp.getString("pwd", "");
        if (!name.isEmpty()){
            useridEt.setText(name);
            passEt.setText(pwd);

            rememberCb.setChecked(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        ServerSession.getInstance().removeHandler(TAG);
    }

    @Override
    public void onClick(View v) {
//        String userid =  useridEt.getText().toString().trim();
//        String pass =  passEt.getText().toString().trim();
//        if(userid.equals("")){
//            promptText.setText(R.string.userIdError);
//            return ;
//        }
//        if(pass.equals("")){
//            promptText.setText(R.string.passError);
//            return ;
//        }
//        WebConstant.digest = ("Basic " + new String(Base64.encode((userid + ':' + pass).getBytes(), Base64.DEFAULT))).replace("\n", "");
//
//        String url = WebConstant.REQUESTPATH+"/users/" + userid+"?getAll=true";
//        OkHttpUtils.get()
//                .url(url).addHeader("Authorization",  WebConstant.digest).addHeader("Accept-Language","zh-CN")
//                .build().execute(new Callback()
//        {
//            @Override
//            public String parseNetworkResponse(Response response, int id) throws Exception {
//                String string = response.body().string();
//                JSONObject jsonObj = new JSONObject(string);
//                if(jsonObj.get("userName")!=null){
//                    WebConstant.userId = (String)jsonObj.get("userId");
//                    WebConstant.userName = (String)jsonObj.get("userName");
//                    return (String) jsonObj.get("userName");
//                }
//                return null;
//            }
//
//            @Override
//            public void onError(Call call, Exception e, int id) {
//                WebConstant.digest = null;
//                promptText.setText(R.string.loginError);
//                Log.i(TAG,e.getMessage());
//                e.printStackTrace();
//            }
//
//            @Override
//            public void onResponse(Object response, int id) {
//                promptText.setText(R.string.loginSuccess+" "+response);
//                Intent intent = new Intent();
//                LogonActivity.this.setResult(WebConstant.RESULT_OK, intent);
//                LogonActivity.this.finish();
//            }
//        });
//        String url="ws://10.0.0.20:8080/hyt/websocket.do?userId=1&userType=2"; //改成自已服务端的地址
//        Request request = new Request.Builder().url(url).build();
//        WebSocketCall webSocketCall = WebSocketCall.create(mOkHttpClient, request);
//        webSocketCall.enqueue(new WebSocketListener() {
//            private final ExecutorService sendExecutor = Executors.newSingleThreadExecutor();
//            private WebSocket webSocket;
//            @Override
//            public void onOpen(WebSocket webSocket, Response response) {
//                Log.d("WebSocketCall", "onOpen");
//                this.webSocket=webSocket;
//            }
//            /**
//             * 连接失败
//             * @param e
//             * @param response Present when the failure is a direct result of the response (e.g., failed
//             * upgrade, non-101 response code, etc.). {@code null} otherwise.
//             */
//            @Override
//            public void onFailure(IOException e, Response response) {
//                Log.d("WebSocketCall","onFailure");
//            }
//
//            /**
//             * 接收到消息
//             * @param message
//             * @throws IOException
//             */
//            @Override
//            public void onMessage(ResponseBody message) throws IOException {
//                final RequestBody response;
//                Log.d("WebSocketCall", "onMessage:" + message.source().readByteString().utf8());
//                if (message.contentType() == WebSocket.TEXT) {//
//                    response = RequestBody.create(WebSocket.TEXT, "你好");//文本格式发送消息
//                } else {
//                    BufferedSource source = message.source();
//                    Log.d("WebSocketCall", "onMessage:" + source.readByteString());
//                    response = RequestBody.create(WebSocket.BINARY, source.readByteString());
//                }
//                message.source().close();
//                sendExecutor.execute(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            Thread.sleep(1000*60);
//                            webSocket.sendMessage(response);//发送消息
//                        } catch (IOException e) {
//                            e.printStackTrace(System.out);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                });
//            }
//
//            @Override
//            public void onPong(Buffer payload) {
//                Log.d("WebSocketCall", "onPong:");
//            }
//
//
//            /**
//             * 关闭
//             * @param code The <a href="http://tools.ietf.org/html/rfc6455#section-7.4.1">RFC-compliant</a>
//             * status code.
//             * @param reason Reason for close or an empty string.
//             */
//            @Override
//            public void onClose(int code, String reason) {
//                sendExecutor.shutdown();
//            }
//        });
        switch (v.getId()){
            case R.id.registerBtn:
            case R.id.loginBtn:
                if (useridEt.getText().toString().isEmpty()){
                    Toast.makeText(this, getResources().getString(R.string.userNameEmptyWarn), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (rememberCb.isChecked()){
                    rememberUserPwd(useridEt.getText().toString(), passEt.getText().toString());
                } else {
                    removeUserPwd();
                }
                mIsRegister = (v.getId() == R.id.registerBtn);
                ServerSession.getInstance().startWebSocket();   // 连接
                break;
            default:
                break;
        }
    }

    private void rememberUserPwd(String name, String pwd){

        //获取SharedPreferences对象
        Context ctx = LogonActivity.this;
        SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
        //存入数据
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("name", name);
        editor.putString("pwd", pwd);
        editor.apply();
    }
    private void removeUserPwd(){

        Context ctx = LogonActivity.this;
        SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        editor.putString("name", "");
        editor.putString("pwd", "");

        editor.apply();
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        long tmNow = System.currentTimeMillis();
        if ((tmNow - mExitTime) > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = tmNow;
        } else {
            finish();
            System.exit(0);
        }
    }
//    public bool OnKeyDown(Keycode keyCode, KeyEvent e)
//    {
//        if (keyCode == Keycode.Back && e.Action == KeyEventActions.Down)//判断点击的是返回键，并且动作是Down按下
//        {
//            if (!firstTime.HasValue || DateTime.Now.Second - firstTime.Value.Second > 2)
//            {
//                Toast.MakeText(this, "再按一次退出", ToastLength.Short).Show();
//                firstTime = DateTime.Now;
//            }
//            else
//            {
//                Finish();//退出应用程序
//            }
//            return true;
//        }
//        return base.OnKeyDown(keyCode,e);
//    }

//    public String getTopActivityName(){
//        ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
//        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
//        return cn.getClassName();
//    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_main, menu);
//        return true;
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        // Handle action bar item clicks here. The action bar will
//        // automatically handle clicks on the Home/Up button, so long
//        // as you specify a parent activity in AndroidManifest.xml.
//        int id = item.getItemId();
//
//        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }
//
//        return super.onOptionsItemSelected(item);
//    }
}